import Sound from 'react-native-sound';
import Log from '../common/log';

interface PlaySoundProps {
  url: string;
  playEnd?: () => void;
  volume?: number;
}

export const playSoundWithUrl = ({
  url,
  playEnd,
  volume = 1
}: PlaySoundProps): Sound => {
  const s = new Sound(url, null, (e): void => {
    if (e) {
      Log.e('ClassRoom play sound', JSON.stringify({ event: 'error', e }));
      return;
    }
    s.play((): void => {
      s.release();
      if (playEnd) {
        playEnd();
      }
    });
    s.setVolume(volume);
  });
  return s;
};

export const prepareSoundWithUrl = (
  url: string,
  currentTime?: number
): Promise<Sound> =>
  new Promise((resolve, reject): void => {
    const s = new Sound(url, null, (e): void => {
      if (e) {
        Log.e(
          'ClassRoom prepare sound error',
          JSON.stringify({ event: 'error', e })
        );
        reject(e);
        return;
      }
      if (currentTime) {
        s.setCurrentTime(currentTime);
      }
      resolve(s);
    });
  });

export const test = (): void => {};
